package cn.jinjimi.app.main.activity;

import android.app.Activity;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Point;
import android.support.v4.content.ContextCompat;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.TextView;

import cn.jinjimi.base.preference.PreferenceManager;
import cn.jinjimi.base.util.FileUtils;
import cn.jinjimi.base.util.ImageUtils;
import cn.jinjimi.base.util.LogUtil;
import cn.jinjimi.base.util.ToastUtils;
import cn.jinjimi.app.R;
import cn.jinjimi.app.bean.QuesCode;
import cn.jinjimi.app.controller.event.PersonalPhotoUploadEvent;
import cn.jinjimi.app.controller.event.ToSelectPhotoEvent;
import cn.jinjimi.app.services.UploadService;
import cn.jinjimi.app.main.dialog.CommAlertDialog;
import cn.jinjimi.app.main.dialog.LoadingDialog;
import cn.jinjimi.app.main.extend.ToolBarCommonActivity;
import cn.jinjimi.app.main.widget.biz.StatePhotoIngDoneView;
import cn.jinjimi.app.main.widget.biz.StatePhotoNormalView;
import cn.jinjimi.app.util.NetworkUtils;
import cn.jinjimi.app.util.PhotoUtils;
import cn.jinjimi.app.bean.SharePrefKeys;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;

/**
 * 诚信通个人形象照
 * 查看
 * 上传
 * 上传状态，进度查看
 * Created by Jinsen on 2015/6/19.
 */
public class PersonalPhotoActivity extends ToolBarCommonActivity {

    StatePhotoNormalView mNormalView = null;

    StatePhotoIngDoneView mIngDoneView = null;

    FrameLayout mStateRootView = null;
    FrameLayout.LayoutParams mFLP = null;
    TextView mPhotoDescTv = null;
    Button mStateBtn = null;

    Dialog mStateDialog = null;
    TextView mDialogAction = null;
    TextView mDialogMsg = null;
    TextView mDialogTitle = null;
    ImageView mDialogIcon = null;


    //上传形象照的当前状态 -1未上传，0审核中，1审核成功，2审核失败， 3处理成功
    int mCurrentState = -1;
    String mPhotoUrl = null;

    int mUploadState = 0;//1正在上传，2上传成功，3上传失败 网络原因 4上传失败，图片不合格

    @Override
    protected void beforeInitView() {
        setContentView(R.layout.activity_personal_photo_layout);

        setTitle(getString(R.string.person_lable));
    }

    @Override
    protected void initial() {
        initView();
        initListener();
    }

    protected void initView() {
        mPhotoDescTv = (TextView) findViewById(R.id.personal_photo_dese_textView);
        mStateRootView = (FrameLayout) findViewById(R.id.personal_photo_state_root);

        mStateBtn = (Button) findViewById(R.id.personal_photo_state_textView);

        mFLP = new FrameLayout.LayoutParams(-1, -1);
        mNormalView = new StatePhotoNormalView(this);
        mIngDoneView = new StatePhotoIngDoneView(this);
        setData();
    }


    private void setData() {
        mNormalView.setPhotoUrl(mPhotoUrl);
        mIngDoneView.setPhotoUrl(mPhotoUrl);
        refreshUiByState();
        if (mCurrentState == -1 && NetworkUtils.getNetworkType(this) != NetworkUtils.NETTYPE_WIFI) {
            networkAlert();
        }
    }

    protected void initListener() {
        mStateBtn.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        super.onClick(v);
        switch (v.getId()) {
            case R.id.personal_photo_state_textView:
                stateAction();
                break;

            case R.id.upload_state_action:
                mStateDialog.dismiss();
                PreferenceManager.removeData(SharePrefKeys.PREF_PERSONAL_PHOTO_UPLOAD_STATE);
                if (mUploadState == 4) {
                    selectPhotoActon();
                } else if (mUploadState == 3) {
                    refreshUiByState();
                }
                break;
            case R.id.dialog_cancel:
                mUploadPicAlertDialog.dismiss();
                break;
            case R.id.dialog_ok://确认上传
                mUploadPicAlertDialog.dismiss();
                uploadPhoto();
                break;
        }
    }

    //根据当前的状态进行相对于的操作
    private void stateAction() {

    }


    private void showStateDialog(int result) {
        mUploadState = result;
        if (mStateDialog == null) {
            mStateDialog = new Dialog(this);
            mStateDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            mStateDialog.setContentView(R.layout.dialog_upload_personalphoto_state_layout);
            mStateDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
            mDialogIcon = (ImageView) mStateDialog.findViewById(R.id.upload_state_title_icon);
            mDialogTitle = (TextView) mStateDialog.findViewById(R.id.upload_state_title);
            mDialogMsg = (TextView) mStateDialog.findViewById(R.id.upload_state_msg);
            mDialogAction = (TextView) mStateDialog.findViewById(R.id.upload_state_action);
            mDialogAction.setOnClickListener(this);
        }
        if (result == 2) {
            mDialogIcon.setImageResource(R.drawable.icon_photo_upload_success);
            mDialogTitle.setText(R.string.upload_succ);
            mDialogTitle.setTextColor(ContextCompat.getColor(PersonalPhotoActivity.this, R.color.green));
            mDialogMsg.setText(R.string.upload_state_succ_msg);
            mDialogAction.setText(R.string.upload_state_succ_action);
        } else if (result == 3) {
            mDialogIcon.setImageResource(R.drawable.icon_photo_upload_failure);
            mDialogTitle.setText(R.string.upload_fail);
            mDialogTitle.setTextColor(ContextCompat.getColor(PersonalPhotoActivity.this, R.color.orange));
            mDialogMsg.setText(R.string.upload_state_fail_net_error_msg);
            mDialogAction.setText(R.string.upload_state_fail_net_error_action);
        } else if (result == 4) {
            mDialogIcon.setImageResource(R.drawable.icon_photo_upload_failure);
            mDialogTitle.setTextColor(ContextCompat.getColor(PersonalPhotoActivity.this, R.color.orange));
            mDialogTitle.setText(R.string.upload_fail);
            mDialogMsg.setText(R.string.upload_state_fail_file_error_msg);
            mDialogAction.setText(R.string.upload_state_fail_file_error_action);
        }

        mStateDialog.setCanceledOnTouchOutside(true);
        mStateDialog.show();
    }

    //根据当前的状态刷新UI界面
    private void refreshUiByState() {
        switch (mCurrentState) {
            case 0:
                checking();
                break;
            case 1:
                checkDone();
                break;
            case 2:
                checkFail();
                break;
            case 3:
                worked();
                break;
            case -1:
            default:
                normal();
                break;
        }
    }

    //未上传
    private void normal() {
        mStateRootView.removeAllViews();
        mStateRootView.addView(mNormalView, mFLP);
        mNormalView.setState(mCurrentState);
        mNormalView.setPhotoBitmap(null);

        mPhotoDescTv.setText(R.string.personal_photo_desc);
        mStateBtn.setText(R.string.personal_photo_upload_action_title);
        mStateBtn.setEnabled(false);
        mUploadState = PreferenceManager.getIntData(SharePrefKeys.PREF_PERSONAL_PHOTO_UPLOAD_STATE);
        if (mUploadState == 1) {
            showUploading();
        }
    }

    //已上传，正在处理中
    private void checking() {
        mStateRootView.removeAllViews();
        mStateRootView.addView(mIngDoneView, mFLP);
        mIngDoneView.setState(mCurrentState);

        mPhotoDescTv.setText(R.string.personal_photo_desc);
        mStateBtn.setText(R.string.personal_photo_upload_action_checking_title);
        mStateBtn.setEnabled(false);
    }

    //审核通过
    private void checkDone() {
        mStateRootView.removeAllViews();
        mStateRootView.addView(mIngDoneView, mFLP);
        mIngDoneView.setState(mCurrentState);

        mPhotoDescTv.setText(R.string.personal_photo_desc);
        mStateBtn.setText(R.string.personal_photo_state);
        mStateBtn.setEnabled(false);
    }

    //审核失败
    private void checkFail() {
        mStateRootView.removeAllViews();
        mStateRootView.addView(mIngDoneView, mFLP);
        mNormalView.setState(mCurrentState);

        mPhotoDescTv.setText(R.string.personal_photo_desc);
        mStateBtn.setText(R.string.personal_photo_state_fail);
        mStateBtn.setEnabled(true);

        mUploadState = PreferenceManager.getIntData(SharePrefKeys.PREF_PERSONAL_PHOTO_UPLOAD_STATE);
        if (mUploadState == 1) {
            showUploading();
        }
    }

    //处理完成
    private void worked() {
        mStateRootView.removeAllViews();
        mStateRootView.addView(mIngDoneView, mFLP);
        mIngDoneView.setState(mCurrentState);

        mPhotoDescTv.setText(R.string.personal_photo_desc);
        mStateBtn.setText(R.string.personal_photo_state_ready);
        mStateBtn.setEnabled(true);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        finish();
    }

    //在非WiFi网络下，提示用户
    private void networkAlert() {
        getAlertDialog().setMessage(getString(R.string.submit))
                .setRightBtn(getString(R.string.ok), new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        getAlertDialog().dismissDialog();
                    }
                });
        getAlertDialog().setCanceledOnTouchOutside(false);
        getAlertDialog().showDialog(CommAlertDialog.Style.ONE_BUTTON);
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
    }

    @Override
    public void finish() {
        setResult(Activity.RESULT_OK);
        super.finish();
    }

    //--------------------------------选择照片-----------------------------------------------\\

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onToSelectPhotoEvent(ToSelectPhotoEvent event) {
        selectPhotoActon();
    }

    private void selectPhotoActon() {
        PhotoUtils.pickUnCompressPhoto(PersonalPhotoActivity.this, false);
    }

    //提示是否上传照片
    Dialog mUploadPicAlertDialog = null;

    //选择照片后上传提示框
    private void uploadPicDialog() {
        mUploadPicAlertDialog = new Dialog(this);
        mUploadPicAlertDialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_photo_upload_layout, null);
        contentView.findViewById(R.id.dialog_ok).setOnClickListener(this);
        contentView.findViewById(R.id.dialog_cancel).setOnClickListener(this);
        mUploadPicAlertDialog.setContentView(contentView);
        mUploadPicAlertDialog.getWindow().setBackgroundDrawableResource(R.color.transparent);
        mUploadPicAlertDialog.setCanceledOnTouchOutside(false);
        mUploadPicAlertDialog.show();
    }

    File mPhotoTempFile = null;
    Bitmap bitmap = null;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        String path = PhotoUtils.handlePhotoResult(this, data, requestCode, resultCode);
        if (path == null) {
            return;
        }
        mPhotoTempFile = new File(path);
        if (Activity.RESULT_OK == resultCode) {
            switch (requestCode) {
                case QuesCode.RequestCodeCamera:
                    try {
                        int sampleSize = 1;
                        if (tooLargeBitmap(mPhotoTempFile.getPath()))
                            sampleSize = 2;
                        bitmap = ImageUtils.getBitmap(mPhotoTempFile.getPath(), sampleSize);

                        if (bitmap == null) {
                            ToastUtils.toastMessage(this, getString(R.string.pick_photo_error));
                            mStateBtn.setEnabled(false);
                            mNormalView.setPhotoBitmap(null);
                            return;
                        }

                        mNormalView.setPhotoBitmap(bitmap);
                        mIngDoneView.setPhotoBitmap(bitmap);

                        mStateBtn.setEnabled(true);
                    } catch (Exception e) {
                        LogUtil.e("PersonalPhotoActivity", "e.printStackTrace()" + e.getMessage(), e);
                        ToastUtils.toastMessage(this, getString(R.string.pick_photo_error));
                        mStateBtn.setEnabled(false);
                    } finally {
                    }
                    break;
                case QuesCode.RequestCodeAlbum:
                    if (path == null || (!path.endsWith(".png") && !path.endsWith(".jpg"))) {
                        ToastUtils.toastMessage(this, getString(R.string.personal_photo_upload_state_type));
                        mStateBtn.setEnabled(false);
                        return;
                    }

                    if (FileUtils.checkSaveLocationExists()) {
                        int sampleSize = 1;
                        if (tooLargeBitmap(mPhotoTempFile.getPath()))
                            sampleSize = 2;
                        bitmap = ImageUtils.getBitmap(mPhotoTempFile.getPath(), sampleSize);
                        mNormalView.setPhotoBitmap(bitmap);
                        mIngDoneView.setPhotoBitmap(bitmap);
                        mStateBtn.setEnabled(true);
                    } else {
                        ToastUtils.toastMessage(this, R.string.pick_photo_no_storage_error);
                    }
                    break;
            }
        }
    }

    public static boolean tooLargeBitmap(String path) {
        Point p = ImageUtils.getSize(path);
        return p.x > 3000 || p.y > 3000;
    }

    private void uploadPhoto() {
        float size = ((float) FileUtils.getFileSize(mPhotoTempFile.getPath())) / 1024 / 1024;
        LogUtil.d("", "select photo size = " + size);
        if (size < 0.5 || size > 10) {
            showStateDialog(4);
            mPhotoTempFile = null;
            mStateBtn.setEnabled(false);
            return;
        }

        mStateRootView.removeAllViews();
        mStateRootView.addView(mIngDoneView, mFLP);
        mIngDoneView.setState(mCurrentState);
        mIngDoneView.setPhotoBitmap(bitmap);

        mStateBtn.setText(R.string.personal_photo_upload_action_uploading_title);
        mStateBtn.setEnabled(false);

        Intent upload = new Intent(this, UploadService.class);
        upload.putExtra("filePath", mPhotoTempFile.getPath());
        startService(upload);
    }

    LoadingDialog loadingDialog = null;

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onPersonalPhotoUploadEvent(PersonalPhotoUploadEvent event) {

    }

    private void showUploading() {
        if (loadingDialog != null) {
            if (loadingDialog.isShowing())
                loadingDialog.dismiss();
            loadingDialog = null;
        }
        loadingDialog = new LoadingDialog(this, getString(R.string.uploading_wait));
        loadingDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                finish();
                return true;
            }
        });
        loadingDialog.setCanceledOnTouchOutside(false);
        loadingDialog.show();
    }

    //---------------------------------------------审核通过并且处理完成-------------------------------------------------//
}
